package com.baseproject.datasource.local.database.dao;

import android.support.annotation.NonNull;
import android.util.Log;

import com.baseproject.datasource.local.database.BaseLocalDatabaseStrategy;
import com.baseproject.util.LogUtils;

import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * Created by hp on 2017/6/14.
 */

public class MyOrmLiteDatabaseStrategy implements BaseLocalDatabaseStrategy {

    private Class getDaoClass(Class entityClass) {
        Class classNameDao = null;
        try {
            classNameDao = Class.forName(entityClass.getName() + "Dao");
        } catch (ClassNotFoundException e) {
            LogUtils.e("[getDaoClass] stack: " + Log.getStackTraceString(e));
        }
        return classNameDao;
    }

    @Override
    public <T> void insertItem(@NonNull T item) {
        Class<T> className = (Class<T>) item.getClass();
        Class classNameDao = getDaoClass(className);
        BaseDaoFactory.getInstance().getBaseDao(classNameDao, className).insert(item);
    }

    @Override
    public <T> void insertItems(@NonNull List<T> items) {
            for (T item : items) {
                insertItem(item);
            }
    }

    @Override
    public <T> void delete(Class<T> className, Map<String, String> where) {
        Class classNameDao = getDaoClass(className);
        BaseDaoFactory.getInstance().getBaseDao(classNameDao, className).delete(buildWhere(where));
    }

    private String buildWhere(Map<String, String> whereMap) {
        if (whereMap == null) {
            return null;
        }
        StringBuilder stringBuilder = new StringBuilder();
        Set<String> keys = whereMap.keySet();
        Iterator<String> iterator = keys.iterator();
        while (iterator.hasNext()) {
            String key = iterator.next();
            String value = whereMap.get(key);
            stringBuilder.append(key + " " + value);
            if (iterator.hasNext()) {
                stringBuilder.append(" and ");
            }
        }
        return stringBuilder.toString();
    }

    @Override
    public <T> void updateItem(@NonNull T item, Map<String, String> where) {
          delete(item.getClass(), where);
          insertItem(item);
    }

    @Override
    public <T> void updateItems(@NonNull List<T> items, Map<String, String> where) {
        delete(items.get(0).getClass(), where);
        insertItems(items);
    }

    @Override
    public <T> List<T> getList(Class<T> className, Map<String, String> where, String[] projections) {
        Class classNameDao = getDaoClass(className);
        List<T> result = BaseDaoFactory.getInstance().getBaseDao(classNameDao, className).query(projections, buildWhere(where));
        return result;
    }
}
